import {ComponentsInfoType, ComponentsStateType} from "./index";

export function getNextSelectedId(fe_id: string, componentList: ComponentsInfoType[]) {
    const visibleComponent = componentList.filter(item => !item.isHidden)
    const index = visibleComponent.findIndex(c => c.fe_id === fe_id)
    let newSelectedId = ''

    const length = visibleComponent.length
    if (length <= 1) {
        newSelectedId = ''
    } else {
        if (index === length - 1) {
            newSelectedId = visibleComponent[index - 1].fe_id
        } else {
            newSelectedId = visibleComponent[index + 1].fe_id
        }
    }
    return newSelectedId

}

export function insertNewComponent(draft: ComponentsStateType, newComponent: ComponentsInfoType) {
    const {selectedId, componentList} = draft
    const index = componentList.findIndex(item => item.fe_id === selectedId)
    if (index < 0) {
        draft.componentList.push(newComponent)
    } else {
        draft.componentList.splice(index + 1, 0, newComponent)
    }
    draft.selectedId = newComponent.fe_id
}